package com.lagou.homework.format;

import com.lagou.homework.module.Word;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;

import java.io.IOException;

@AllArgsConstructor
@NoArgsConstructor
public class WordSortWriter extends RecordWriter<Word, NullWritable> {

    private FSDataOutputStream outputStream;

    private static int RANK = 1;

    @Override
    public void write(Word word, NullWritable nullWritable) throws IOException {
        outputStream.write(new Word(getRANK(), word.getWord()).toString().getBytes());
        outputStream.write("\r\n".getBytes());
        outputStream.flush();
    }

    @Override
    public void close(TaskAttemptContext taskAttemptContext) {
        IOUtils.closeStream(outputStream);
    }

    public static int getRANK() {
        return RANK ++;
    }
}
